<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace app\common\lib\exception;

use think\exception\Handle;
use think\facade\Log;

class ApiHandleException extends Handle
{
    private $code;
    private $msg;
    private $httpCode = 200;

    /**
     * @Desc: 继承exception类
     *
     * @param \Exception $ex
     *
     * @return \think\Response|\think\response\Json
     *
     * @User: Randy_chen
     * @Date: 2019/5/16
     * @Time: 14:37
     */
    public function render(\Exception $ex)
    {
        if ($ex instanceof BaseException) {
            $this->code     = $ex->code;
            $this->msg      = $ex->msg;
            $this->httpCode = $ex->httpCode;
        } else {
            if (config('app.app_debug')) {
//                return $this->show(1, $ex->getMessage(), []);
                return parent::render($ex);
            }
            $this->httpCode = 500;
            return $this->show(1, $ex->getMessage(), []);
        }

        json_return($this->code , $this->msg , ['url'=>\think\facade\Request::url()]);
    }

    /**
     * 通用化API接口数据输出.
     *
     * @param int    $status   业务状态码
     * @param string $message  信息提示
     * @param array  $data     数据
     * @param int    $httpCode http状态码
     *
     * @return mixed
     */
    public function show($status, $message, $data = [], $httpCode = 200)
    {
        $data =  [
            'code' => $status,
            'msg'  => $message,
            'data' => $data,
        ];
        $httpCode = $httpCode ?: $this->httpCode;

        return json($data, $httpCode);
    }

    /**
     * @Desc: 自定义错误日志
     *
     * @param \Exception $ex
     *
     * @User: Randy_chen
     * @Date: 2019/5/16
     * @Time: 14:38
     */
    private function recordErrorLog(\Exception $ex)
    {
        Log::init([
            'type'  => 'File',
            'path'  => LOG_PATH,
            'level' => ['error'],
        ]);
        Log::record($ex->getMessage(), 'error');
    }
}
